package com.asuka.service.impl;

import com.asuka.context.BaseContext;
import com.asuka.entity.AddressBook;
import com.asuka.mapper.AddressBookMapper;
import com.asuka.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService{

    @Autowired
    private AddressBookMapper addressBookMapper;


    @Override
    public void insert(AddressBook addressBook) {
        addressBookMapper.insert(addressBook);
    }


    @Override
    public List<AddressBook> selectListByUserId() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .build();

        return addressBookMapper.selectList(addressBook);
    }


    @Override
    public AddressBook selectDefaultAdress() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(1)
                .build();

        return addressBookMapper.selectList(addressBook).get(0);
    }


    @Override
    public void updateById(AddressBook address) {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .build();

        addressBookMapper.update(address);
    }


    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook selectById(Long id) {
        AddressBook address = AddressBook.builder()
                .id(id)
                .build();

        List<AddressBook> list = addressBookMapper.selectList(address);

        return list.get(0);
    }

    @Override
    @Transient
    public void updateDefaultAdress(Long id) {
        AddressBook address = AddressBook.builder()
                .id(id)
                .userId(BaseContext.getCurrentId())
                .isDefault(1)
                .build();

        addressBookMapper.updateDefaultAdress(BaseContext.getCurrentId());
        addressBookMapper.update(address);

    }



}
